package com.tencent.service.impl;

import com.tencent.mapper.LoginMapper;
import com.tencent.entity.Role;
import com.tencent.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @BelongsProject: health
 * @BelongsPackage: com.tencent.service
 * @ClassName: LoginDetailsService
 * @Description: TODO
 * @Version: 1.0.0
 * @CreateTime: 2022-08-12  14:02
 * @Author: Yangjx
 */
@Service
public class LoginDetailsService implements UserDetailsService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过输入的用户名查询用户
        User user = loginMapper.findByUsername(username);

        //基于查询到的用户中的用户id，通过用户中间表查询到改用户对应的角色权限
        Integer roleId = loginMapper.findByUserId(user.getId());//通过用户id在关系表中查到对应角色id
        Role role = loginMapper.findByRoleId(roleId);//用户对应的角色
        String keyword = role.getKeyword();//角色权限

        //角色权限赋给user
        user.setRole(keyword);

        //查不到用户(用户名错误)会出现空指针，增加异常处理器捕获
        return org.springframework.security.core.userdetails.User//框架下的User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                //权限赋值
                .authorities(user.getRole())
                .build();
    }
}
